package com.itheima.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.itheima.tanhua.dubbo.utils.IdWorker;
import com.itheima.tanhua.dubbo.utils.MovementTimeLineService;
import com.itheima.tanhua.model.domain.PageResult;
import com.itheima.tanhua.model.mongo.Friend;
import com.itheima.tanhua.model.mongo.Movement;
import com.itheima.tanhua.model.mongo.MovementTimeLine;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.awt.image.CropImageFilter;
import java.util.List;

@DubboService
public class MovementsApiImpl implements MovementsApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private MovementTimeLineService movementTimeLineService;

    @Override
    public void publishMovements(Movement movement) {

        //保存动态详情
        movement.setCreated(System.currentTimeMillis());
        movement.setPid(idWorker.getNextId("movement"));

        mongoTemplate.save(movement);

//        //查找用户好友信息
//        Criteria criteria = Criteria.where("userId").is(movement.getUserId());
//        Query query = Query.query(criteria);
//        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
//        //存入到时间线表中
//        for (Friend friend : friendList) {
//            MovementTimeLine movementTimeLine = new MovementTimeLine();
//            movementTimeLine.setMovementId(movement.getId());
//            movementTimeLine.setUserId(movement.getUserId());
//            movementTimeLine.setFriendId(friend.getFriendId());
//            movementTimeLine.setCreated(System.currentTimeMillis());
//            mongoTemplate.save(movementTimeLine);
//        }

        movementTimeLineService.saveTimeLine(movement);
    }

    @Override
    public PageResult findByUserId(Integer page, Integer pagesize, Long userId) {

        Query query = Query.query(Criteria.where("userId").is(userId))
                .skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);

        PageResult pageResult = new PageResult();


        return new PageResult(page, pagesize, 0, movements);
    }

    @Override
    public List<Movement> findTimeLine(Integer page, Integer pagesize, Long userId) {
        //根据用户id分页查询动态时间线表
        Query query = Query.query(Criteria.where("friendId").is(userId))
                .skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));

        List<MovementTimeLine> movementTimeLines = mongoTemplate.find(query, MovementTimeLine.class);

        //获取时间线表中的动态id
        List<ObjectId> movementIds = CollUtil.getFieldValues(movementTimeLines, "movementId", ObjectId.class);

        //再查询除动态详情
        Query q = Query.query(Criteria.where("id").in(movementIds));

        List<Movement> movements = mongoTemplate.find(q, Movement.class);

        return movements;
    }

    /**
     * 随机查询指定条数的数据
     * @param counts
     * @return
     */
    @Override
    public List<Movement> randomMovements(Integer counts) {
        //创建统计对象，设计统计参数
        TypedAggregation aggregation = Aggregation.newAggregation(Movement.class,
                Aggregation.sample(counts));

        //调用mongoTemplate方法统计
        AggregationResults<Movement> movements = mongoTemplate.aggregate(aggregation,Movement.class);

        //返回统计结果
        return movements.getMappedResults();
    }

    @Override
    public List<Movement> findMovementsByPids(List<Long> pids) {
        Query query = Query.query(Criteria.where("pid").in(pids));

        List<Movement> list = mongoTemplate.find(query, Movement.class);

        return list;
    }

    @Override
    public Movement findByMovmentId(String id) {
        Query query = Query.query(Criteria.where("id").is(id));

       return mongoTemplate.findOne(query, Movement.class);

//       return mongoTemplate.findById(id,Movement.class);
    }
}
